import React, { useState, useEffect } from "react";
import "../css/global.css";
import { useNavigate } from "react-router-dom";
import styles from "../css/Shopping.module.css";
import { Checkbox, Stepper, Loading, SubmitBar, Toast } from "react-vant";
import { Link } from "react-router-dom";
import axios from "axios";

export default function ShoppingCart() {
  const navigate = useNavigate();
  const [products, setProducts] = useState([]); 
  const [cartItems, setCartItems] = useState([]); 
  const [selectedItems, setSelectedItems] = useState([]);
  const [selectAll, setSelectAll] = useState(false);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const [indexRes, cartRes] = await Promise.all([
          axios.post("/mobile/index"),
          axios.post("/mobile/shopping", { id: "79" }),
        ]);
        setProducts(indexRes.data.data?.commodity || []);
        setCartItems(cartRes.data.data || []);
      } catch (err) {
        console.error("请求失败:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  const calculateTotal = () => {
    return selectedItems.reduce((total, item) => {
      return total + item.commodity[0].price * item.commodity[0].num;
    }, 0);
  };

  const handleQuantityChange = (value, item) => {
    const updatedCartItems = cartItems.map((cartItem) => {
      if (cartItem.id === item.id) {
        return {
          ...cartItem,
          commodity: [
            {
              ...cartItem.commodity[0],
              num: value,
            },
          ],
        };
      }
      return cartItem;
    });
    setCartItems(updatedCartItems);

    if (selectedItems.some((selected) => selected.id === item.id)) {
      setSelectedItems(
        selectedItems.map((selected) =>
          selected.id === item.id
            ? {
                ...selected,
                commodity: [
                  {
                    ...selected.commodity[0],
                    num: value,
                  },
                ],
              }
            : selected
        )
      );
    }
  };

  const handleRemoveFromCart = (productId, e) => {
    e.stopPropagation();
    const itemToRemove = cartItems.find(
      (item) => item.commodity_id == productId
    );

    if (itemToRemove) {
      axios
        .post("mobile/shopping/del", {
          id: itemToRemove.id,
        })
        .then((response) => {
          const updatedCartItems = cartItems.filter(
            (item) => item.id !== itemToRemove.id
          );
          setCartItems(updatedCartItems);

          setSelectedItems(
            selectedItems.filter((item) => item.id !== itemToRemove.id)
          );

          Toast.success("商品已移出购物车");
        })
        .catch((error) => {
          console.error("接口请求失败", error);
          Toast.fail("操作失败");
        });
    }
  };

  const handleAddToCart = (product, e) => {
    e.stopPropagation();
    const userId = JSON.parse(sessionStorage.getItem("user"))?.id;

    if (!userId) {
      Toast.fail("请先登录");
      return;
    }

    axios
      .post("mobile/shopping/add", {
        commodity_id: product.id,
        user_id: userId,
        num: 1,
      })
      .then((response) => {
        const newCartItem = {
          ...response.data.data, 
          commodity: [product],
        };
        setCartItems([...cartItems, newCartItem]);
        Toast.success("商品已添加到购物车");
      })
      .catch((error) => {
        console.error("接口请求失败", error);
        Toast.fail("添加失败");
      });
  };

  const isInCart = (productId) => {
    return cartItems.some(
      (item) => String(item.commodity_id) === String(productId)
    );
  };

  if (loading) {
    return (
      <Loading
        style={{
          display: "inline-flex",
          position: "fixed",
          left: "50%",
          top: "50%",
          transform: "translate(-50%, -50%)",
        }}
        size="24px"
        vertical
      >
        加载中...
      </Loading>
    );
  }

  return (
    <div className="body">
      <div className={styles.title}>购物车</div>
      <div className={styles.cartContainer}>
        {cartItems.length === 0 ? (
          <div className={styles.errorMessage}>
            <p>暂无商品</p>
          </div>
        ) : (
          cartItems.map((item) => (
            <div className={styles.cartList} key={item.id}>
              <div className={styles.cartItem}>
                <Checkbox
                  checkedColor={"#DDAE78"}
                  checked={selectedItems.some(
                    (selected) => selected.id === item.id
                  )}
                  onChange={(checked) => {
                    if (checked) {
                      setSelectedItems([...selectedItems, item]);
                    } else {
                      setSelectedItems(
                        selectedItems.filter(
                          (selected) => selected.id !== item.id
                        )
                      );
                      setSelectAll(false);
                    }
                  }}
                />
                <div className={styles.itemImageBox}>
                  <img
                    src={"http://jingxun.kuxia.top/" + item.commodity[0].image}
                    className={styles.itemImage}
                    alt={item.commodity[0].title}
                  />
                </div>
                <div className={styles.itemInfo}>
                  <h3 className={styles.itemName}>{item.commodity[0].title}</h3>
                  <div className={styles.priceContainer}>
                    <div>
                      <span className={styles.currentPrice}>
                        ￥{item.commodity[0].price}
                      </span>
                    </div>
                    <Stepper
                      value={item.commodity[0].num}
                      onChange={(value) => handleQuantityChange(value, item)}
                      inputWidth="40px"
                      buttonSize="20px"
                      longPress={true}
                      className={styles.stepperStyle}
                    />
                  </div>
                </div>
              </div>
            </div>
          ))
        )}
      </div>

      {/* 瀑布流 */}
      <div className={styles.commodity}>
        {products.map((product) => (
          <div
            key={product.id}
            onClick={() => navigate(`/details/${product.id}`)}
            className={styles.waterfall_box}
          >
            <img
              src={`http://jingxun.kuxia.top/${product.image}`}
              alt={product.title}
            />
            <p className={styles.goods_name}>{product.title}</p>
            <div className={styles.commodity_price}>
              <p className={styles.commodity_price_font}>
                <span className={styles.hot_goods_price_font}>￥</span>
                {product.price}
              </p>
              {isInCart(product.id) ? (
                <img
                  src={require("../img/check-circle.png")}
                  onClick={(e) => handleRemoveFromCart(product.id, e)}
                  alt="已在购物车"
                  className={styles.cartButton}
                />
              ) : (
                <img
                  onClick={(e) => handleAddToCart(product, e)}
                  src={require("../img/accretion.png")}
                  alt="加入购物车"
                  className={styles.cartButton}
                />
              )}
            </div>
          </div>
        ))}
      </div>

      <SubmitBar
        style={{ marginBottom: "45px" }}
        price={calculateTotal() * 100}
        buttonText="提交订单"
        onSubmit={() => {
          if (selectedItems.length === 0) {
            Toast.fail("请选择商品");
            return;
          }
          console.log("提交订单:", selectedItems);
        }}
      >
        <Checkbox
          checkedColor={"#DDAE78"}
          checked={selectAll}
          onChange={(checked) => {
            setSelectAll(checked);
            setSelectedItems(checked ? [...cartItems] : []);
          }}
        >
          全选
        </Checkbox>
      </SubmitBar>

      {/* 底部导航栏 */}
      <div className={styles.bottom_navigation}>
        <div className={styles.bottom_navigation_option}>
          <Link to="/home">
            <img src={require("../img/home.png")} alt="首页" />
            <p>首页</p>
          </Link>
        </div>
        <div className={styles.bottom_navigation_option}>
          <img src={require("../img/list_bulleted.png")} alt="分类" />
          <p>分类</p>
        </div>
        <div className={styles.bottom_navigation_option}>
          <img
            className={styles.navigation_active}
            src={require("../img/shopping cart.png")}
            alt="购物车"
          />
          <p className={styles.navigation_active}>购物车</p>
        </div>
        <div className={styles.bottom_navigation_option}>
          <Link to="/Mine">
            <img src={require("../img/person.png")} alt="我的" />
            <p>我的</p>
          </Link>
        </div>
      </div>
    </div>
  );
}
